/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package JFreeChartExtensions.chartextensions.zooming;

import JFreeChartExtensions.ExtendableChartPanel;
import JFreeChartExtensions.chartextensions.IChartExtensionManager;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.JComponent;
import org.jfree.chart.ChartPanel;

/**
 *
 * @author Nobody
 */
public class ChartZoomingManager implements MouseWheelListener, IChartExtensionManager {

    protected boolean ignore = false;
    protected int zoomFactor = 0;
    protected ExtendableChartPanel chartPanel;

    public int getZoomFactor() {
        return zoomFactor;
    }

    public boolean isIgnore() {
        return ignore;
    }

    public void setIgnore(boolean ignore) {
        this.ignore = ignore;
    }

    @Override
    public void mouseWheelMoved(MouseWheelEvent e) {
        setIgnore(true);
        if (e.getScrollType() != MouseWheelEvent.WHEEL_UNIT_SCROLL) {
            return;
        }
        if (e.getWheelRotation() < 0) {
            increaseZoom((ChartPanel) e.getComponent(), true);
        } else {
            decreaseZoom((ChartPanel) e.getComponent(), true);
        }
        setIgnore(false);

    }

    public synchronized void increaseZoom(JComponent chart, boolean saveAction) {
        ChartPanel ch = (ChartPanel) chart;
        zoomChartAxis(ch, true);

    }

    public synchronized void decreaseZoom(JComponent chart, boolean saveAction) {
        ChartPanel ch = (ChartPanel) chart;
        zoomChartAxis(ch, false);
    }

    private void zoomChartAxis(ChartPanel chartP, boolean increase) {
        int width = chartP.getMaximumDrawWidth() - chartP.getMinimumDrawWidth();
        int height = chartP.getMaximumDrawHeight() - chartP.getMinimumDrawWidth();
        if (increase) {
            chartP.zoomInBoth(width / 2, height / 2);
            ++zoomFactor;
        } else {
            chartP.zoomOutBoth(width / 2, height / 2);
            --zoomFactor;
        }
    }

    @Override
    public void register(ChartPanel chartPanel) {
        this.chartPanel = (ExtendableChartPanel) chartPanel;
        chartPanel.addMouseWheelListener(this);
    }

    @Override
    public void unregister() {
        chartPanel.removeMouseWheelListener(this);
    }
}
